package org.third.common.utils;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

/**
 * Created by xuali on 3/29/2018.
 */
@Component
public class HttpRequestUtil {
    private static final Logger logger = LoggerFactory.getLogger(VaultAndKubeRequestUtil.class);

    private RestTemplate restTemplate = new RestTemplate(getrRequestFactory());

    public HttpRequestUtil() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    }

    private ClientHttpRequestFactory getrRequestFactory() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        int timeout = 2000;
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory =
                new HttpComponentsClientHttpRequestFactory();
        CloseableHttpClient httpclient = HttpClientUtils.getCertificateIngnoredHttpClient();
        clientHttpRequestFactory.setConnectTimeout(timeout);
        clientHttpRequestFactory.setHttpClient(httpclient);
        return clientHttpRequestFactory;
    }



    public <T, S, V> ResponseEntity callHttpsRquest(HttpMethod method, String uri, String token, T body, Class<S> responseClass, V... uriVariables) {

        HttpEntity entity = new HttpBuilder()
                .buildEntityWithBody(body);
        if (!StringUtils.isEmpty(token)){
            entity = new HttpBuilder()
                    .setHeader("Authorization","Bearer " + token)
                    .buildEntityWithBody(body);
        }

        logger.info("request to uri {} header {},and body {}", uri, entity.getHeaders(),
                entity.getBody());

        ResponseEntity responseEntity = null;
        if (uriVariables == null) {
            responseEntity = restTemplate.exchange(uri, method, entity, responseClass);
        } else {
            responseEntity = restTemplate.exchange(uri, method, entity, responseClass, uriVariables);
        }


        logger.info("call response status code {}",responseEntity.getStatusCode());
        logger.info("call response status info {}",responseEntity.getStatusCodeValue());
        logger.info("call response message {}",responseEntity.getBody());

        return responseEntity;
    }
}
